/*!
 * This file aims to draw the main window of the application
 * @file mainwindow.h
 * @file cfgparser/cfgparser.h
 * @file forms/newdb/newdb.h
 * @author Mazzer Yannis, Calingarayar Martial
 */

#include <QtGui>
#include <QTreeWidget>
#include <QTreeView>
#include <QTableView>
#include <QToolBox>

#include "mainwindow.h"
#include "types/movies.h"
#include "types/albums.h"
#include "cfgparser/cfgparser.h"
#include "forms/newdb/newdb.h"
#include "liteconnector/liteconnector.h"

/*
 *
 *
 */

MainWindow::MainWindow()
{
  /*
   * test of the cfgparser part

  Config cfg(QString(".qmlrc"));
  QString cfgtestvalue;
  QString dbg;

  qDebug() << "test1";

  cfg.get(QString("test2"), cfgtestvalue);
  qDebug() << "test2";

mediaList->addItems(QStringList()
		    << cfgtestvalue);
  */
  createActions();
  createMenu();
  createDocks();
  createStatusBar();
  cfg = new Config();
  const QString cfgType = cfg->get(QString("Type"), NULL);
  const QString cfgHost = cfg->get(QString("Hostname"), NULL);
  const QString cfgName = cfg->get(QString("DatabaseName"), NULL);
  const QString cfgPort = cfg->get(QString("Port"), NULL);
  const QString cfgUser = cfg->get(QString("User"), NULL);
  const QString cfgNick = cfg->get(QString("Nick"), NULL);
  const QString cfgComm = cfg->get(QString("Comment"), NULL);

  if( cfgType != NULL &&
      cfgHost != NULL &&
      cfgName != NULL &&
      cfgPort != NULL &&
      cfgUser != NULL &&
      cfgNick != NULL &&
      cfgComm != NULL)
  {
    this->newdbslot(cfgType,
		    cfgHost,
		    cfgName,
		    cfgPort,
		    cfgUser,
		    cfgNick,
		    cfgComm);
  }
  else
    this->newdbslot();

}

MainWindow::~MainWindow()
{
}

/*
 * This parts is the implementation of the
 * PRIVATE SLOTS
 */

void MainWindow::about()
{
    /* This could be a good idea to include a file here instead of
     * using a hard-coded description
     */
  QMessageBox::about(this, tr("About this application"),
		     tr("This is going to be the <b>best</b> media "
			"managing application over the <u>entire world</u> !"));


}

void MainWindow::newdbslot()
{
	dbDialog = new newdbDialog(this);
	connect(dbDialog, SIGNAL(accepted()), this, SLOT(fillLists()));
}

void MainWindow::newdbslot(newdbDialog *dialog)
{
	dbDialog = new newdbDialog(dialog, this);
	connect(dbDialog, SIGNAL(accepted()), this, SLOT(fillLists()));
}

void MainWindow::newdbslot(const QString &type,
			   const QString &host,
			   const QString &name,
			   const QString &port,
			   const QString &user,
			   const QString &nick,
			   const QString &comm)
{
    dbDialog = new newdbDialog(type, host, name, port, user, nick, comm, this);
    connect(dbDialog, SIGNAL(accepted()), this, SLOT(fillLists()));
}

void MainWindow::newMovieSlot()
{
    QSqlRecord tmp;
    QSqlQuery q;
    q.exec("SELECT MAX(numero) FROM \"Media\"");
    q.next();
    int id = (q.value(0).toInt()) + 1;
    qDebug() << id;
    if(movieModel->insertRow(movieModel->rowCount()))
    {
	movieModel->setData(movieModel->index(movieModel->rowCount()-1,0), id);
	q.prepare("INSERT INTO \"Media\" VALUES(:num, 'Film')");
	q.bindValue(":num", id);
	q.exec();
	updateMovieView(movieModel->index(movieModel->rowCount()-1, 0));
    }
    else
	QMessageBox::about(this,
			   tr("SQL Error"),
			   QString("Erreur:")+= movieModel->lastError().text());
}

void MainWindow::newAlbumSlot()
{
QSqlRecord tmp;
    QSqlQuery q;
    q.exec("SELECT MAX(numero) FROM \"Media\"");
    q.next();
    int id = (q.value(0).toInt()) + 1;
    qDebug() << id;
    if(albumModel->insertRow(albumModel->rowCount()))
    {
	albumModel->setData(albumModel->index(albumModel->rowCount()-1,0), id);
	q.prepare("INSERT INTO \"Media\" VALUES(:num, 'Album')");
	q.bindValue(":num", id);
	q.exec();
	updateAlbumView(albumModel->index(albumModel->rowCount()-1, 0));
    }
    else
	QMessageBox::about(this,
			   tr("SQL Error"),
			   QString("Erreur:")+= albumModel->lastError().text());

}

void MainWindow::deleteSlot()
{
    this->setCentralWidget((QWidget *)NULL);
    if(currentMedia == currentMovie) {
	movieModel->removeRow(currentMovie->getIndex());
	movieModel->submitAll();
    }
    else if(currentMedia == currentAlbum) {
	albumModel->removeRow(currentAlbum->getIndex());
	albumModel->submitAll();
    }
    delete currentMedia;

}

void MainWindow::fillLists()
{
    this->currentDb = dbDialog->setUpDatabase();
    if(currentDb != NULL) {

	QString connectedMess = tr("Connected to ");
	connectedMess += this->currentDb->getNickName();
	statusBar()->showMessage(connectedMess);
	this->dbList->addItem(currentDb);

	this->movieModel=this->currentDb->retrieveMovies();
	this->movieView->setModel(movieModel);
	this->movieView->hideColumn(0);
	this->movieView->hideColumn(2);
	this->movieView->hideColumn(3);
	this->movieView->hideColumn(4);
	this->movieView->hideColumn(5);
	this->movieView->hideColumn(6);
	this->movieView->hideColumn(7);
	this->movieView->hideColumn(8);
	this->movieView->hideColumn(9);
	this->movieView->setEditTriggers(QAbstractItemView::NoEditTriggers);
	connect(this->movieView, SIGNAL(activated(QModelIndex)),
		this, SLOT(updateMovieView(QModelIndex)));

	this->albumModel=this->currentDb->retrieveAlbums();
	this->albumsView->setModel(albumModel);
	this->albumsView->hideColumn(0);
	this->albumsView->hideColumn(2);
	this->albumsView->hideColumn(3);
	this->albumsView->hideColumn(4);
	this->albumsView->hideColumn(5);
	this->albumsView->hideColumn(6);
	this->albumsView->hideColumn(7);
	this->albumsView->setEditTriggers(QAbstractItemView::NoEditTriggers);
	connect(this->albumsView, SIGNAL(activated(QModelIndex)),
		this, SLOT(updateAlbumView(QModelIndex)));
    }
    else {
    	this->newdbslot(this->dbDialog);
    }
}

void MainWindow::updateMovieView(const QModelIndex &index)
{

//    if(currentMovie != NULL)
//    {
//	delete currentMovie;
//    }
    currentMovie = new Movie(this);
    currentMedia = currentMovie;
    currentMovie->setModelIndex(index, movieModel);
    this->setCentralWidget(currentMovie);
    currentMovie->setMinimumSize(600, 405);


//    bool ok = false;
//    for(int i = 0; i < openedMovies.size(); i++) {
//	if(openedMovies[i]->pindex() == index) {
//	    int idx = central->indexOf(openedMovies[i]);
//	    central->setCurrentIndex(idx);
//	    ok = true;
//	}
//    }
//    if(!ok) {
//	Movie *movieDetails = new Movie(this);
//	movieDetails->setModelIndex(index, movieModel);
//	openedMovies.append(movieDetails);
//	this->central->addTab(movieDetails, movieDetails->getTitle());
//    }



//    Movie *movieDetails = this->movieModel->getMovie(index);
//    int idx = central->indexOf(movieDetails);
//    if(idx == -1) {
//	central->addTab(movieDetails, movieDetails->getTitle());
//	central->setCurrentIndex(central->currentIndex() + 1);
//    }
//    else {
//	central->setCurrentIndex(idx);
//    }

}

void MainWindow::updateAlbumView(const QModelIndex &index)
{
    currentAlbum = new Album(this);
    currentMedia = currentAlbum;
    currentAlbum->setModelIndex(index, albumModel);
    this->setCentralWidget(currentAlbum);
    currentAlbum->setMinimumSize(600, 405);

//    for (int i = 0; i < openedAlbums.size(); i++) {
//	if(openedAlbums[i]->getIndex() == index) {
//	    int idx = central->indexOf(openedAlbums[i]);
//	    central->setCurrentIndex(idx);
//	    goto done;
//	}
//    }
//    Album *albumDetails = new Album(this);
//    albumDetails->setModelIndex(index);
//    openedAlbums.append(albumDetails);



//    Album *albumDetails = this->albumModel->getAlbum(index);
//    int idx = central->indexOf(albumDetails);
//    if(idx == -1) {
//	central->addTab(albumDetails, albumDetails->getTitle());
//	central->setCurrentIndex(central->currentIndex() + 1);
//    }
//    else {
//	central->setCurrentIndex(idx);
//    }
//    done:
//    return;
}

void MainWindow::closeActiveTab()
{
    int idx = this->central->currentIndex();
    if(idx != -1)
	this->central->removeTab(idx);
}

void MainWindow::connectToDbFromList(QModelIndex idx)
{

}

/*
 * This part is the implementation of the
 * PRIVATE variables
 */

void MainWindow::createActions()
{
  newdbAct = new QAction(tr("&Add a Database"), this);
  newdbAct->setShortcut(tr("Ctrl+A"));
  newdbAct->setStatusTip(tr("Open a form to add a database"));
  connect(newdbAct, SIGNAL(triggered()), this, SLOT(newdbslot()));

  quitAct = new QAction(tr("&Quit"), this);
  quitAct->setShortcut(tr("Ctrl+Q"));
  quitAct->setStatusTip(tr("Simply quit the application"));
  connect(quitAct, SIGNAL(triggered()), this, SLOT(close()));

  newMovieAct = new QAction(tr("Add a &Movie"), this);
  newMovieAct->setShortcut(tr("Ctrl+M"));
  newMovieAct->setStatusTip(tr("Add a Movie to the current database"));
  connect(newMovieAct, SIGNAL(triggered()), this, SLOT(newMovieSlot()));

  newAlbumAct = new QAction(tr("Add an A&lbum"), this);
  newAlbumAct->setShortcut(tr("Ctrl+L"));
  newAlbumAct->setStatusTip(tr("Add an Album to the current database")),
  connect(newAlbumAct, SIGNAL(triggered()), this, SLOT(newAlbumSlot()));

  deleteAct = new QAction(tr("&Delete"), this);
  deleteAct->setShortcut(tr("Ctrl+D"));
  deleteAct->setStatusTip(tr("Delete the currently viewable Media"));
  connect(deleteAct, SIGNAL(triggered()), this, SLOT(deleteSlot()));

  aboutAct = new QAction(tr("&About"), this);
  aboutAct->setStatusTip(tr("Show the application About box"));
  connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));

  aboutQtAct = new QAction(tr("About &Qt4"), this);
  aboutQtAct->setStatusTip(tr("Show the Qt4 application About box"));
  connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));


}

void MainWindow::createStatusBar()
{
  statusBar()->showMessage(tr("Welcome to this application"));
}

void MainWindow::createDocks()
{
	dbDock = new QDockWidget(tr("Databases"), this);
	dbDock->setAllowedAreas(Qt::LeftDockWidgetArea
				| Qt::RightDockWidgetArea
				| Qt::TopDockWidgetArea
				| Qt::BottomDockWidgetArea);

	dbList = new QListWidget(dbDock);
	dbDock->setWidget(dbList);
	addDockWidget(Qt::LeftDockWidgetArea, dbDock);
	connect(dbList, SIGNAL(activated(QModelIndex)),
		this, SLOT(connectToDbFromList(QModelIndex)));
	viewMenu->addAction(dbDock->toggleViewAction());

	contentDock = new QDockWidget(tr("Content"),this);
	contentDock->setAllowedAreas(Qt::LeftDockWidgetArea
				   | Qt::RightDockWidgetArea
				   | Qt::TopDockWidgetArea
				   | Qt::BottomDockWidgetArea);

	contentBox = new QToolBox(contentDock);
	contentDock->setWidget(contentBox);
	movieView = new QTreeView(contentBox);
	contentBox->addItem(movieView, QString(tr("Movies")));
	albumsView = new QTreeView(contentBox);
	contentBox->addItem(albumsView, QString(tr("Albums")));
	addDockWidget(Qt::LeftDockWidgetArea, contentDock);
	viewMenu->addAction(contentDock->toggleViewAction());

}

void MainWindow::createMenu()
{
  fileMenu = menuBar()->addMenu(tr("&File"));
  fileMenu->addAction(newdbAct);
  fileMenu->addSeparator();
  fileMenu->addAction(quitAct);

  editMenu = menuBar()->addMenu(tr("&Edit"));
  editMenu->addAction(newMovieAct);
  editMenu->addAction(newAlbumAct);
  editMenu->addAction(deleteAct);

  viewMenu = menuBar()->addMenu(tr("&View"));

  helpMenu = menuBar()->addMenu(tr("&Help"));
  helpMenu->addAction(aboutAct);
  helpMenu->addAction(aboutQtAct);


}
